package top.yaofengqiao.springcloudsimple.mybatisplus.starter.plugins;

import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Statement;


/**
 * @author yfq
 * @date 2024/6/18 15:06
 * @description 慢sql记录插件
 */
@Intercepts({
        @Signature(type = StatementHandler.class, method = "query", args = {Statement.class, ResultHandler.class})
})
public class SlowSqlInnerInterceptor implements Interceptor {
    private final Logger logger = LoggerFactory.getLogger(SlowSqlInnerInterceptor.class);

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        long start = System.currentTimeMillis();

        Object result = invocation.proceed();

        long end = System.currentTimeMillis();

        long cost = end - start;
        if (cost >= 0) {
            String sql = getSql(invocation.getTarget());
            logger.info("slow sql：{}，执行时间：{}ms", sql, end - start);
        }

        return result;
    }

    /**
     * 获取sql(带占位符)
     */
    private String getSql(Object target) {
        try {
            // 获取 StatementHandler 对象
            StatementHandler statementHandler = (StatementHandler) target;
            // 获取 BoundSql 对象
            BoundSql boundSql = statementHandler.getBoundSql();

            return boundSql.getSql();
        } catch (Exception e) {
            return "";
        }
    }

}
